<script setup>
import {onMounted, ref, watch} from "vue";
// 定义属性
const props = defineProps({
  // 这里一定要使用 modelValue ，否则无法双向绑定
  // 父组件中，使用 v-model 进行绑定数据
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '提示'
  },
  size: {
    type: String,
    default: '30%'
  },
  // 'rtl' | 'ltr' | 'ttb' | 'btt'
  direction: {
    type: String,
    default: 'rtl'
  }
});
// 定义事件
const emits = defineEmits(['update:modelValue', 'close', 'confirm', 'open']);

// 定义变量
const drawer = ref({
  visible: props.modelValue,
  title: props.title,
  size: props.size,
  direction: props.direction
});

// 初始化方法
onMounted(() => {
  initialValue();
});
// 监听属性变化
watch(() => props.modelValue, (newVal) => {
  initialValue(newVal);
  console.log('dialog.value===>', drawer.value);
}, {deep: true});
// 初始化变量值
const initialValue = (visible) => {
  drawer.value.visible = visible || props.modelValue;
  drawer.value.title = props.title;
  drawer.value.size = props.size;
  drawer.value.direction = props.direction;
};
// 关闭事件
const close = () => {
  drawer.value.visible = false;
  // 关闭弹出框的时候，需要通知父组件更新 v-model 绑定的数据
  emits('update:modelValue', false);
  emits('close', false);
};
const open = () => {
  emits('open');
};
// 确定事件
const confirm = () => {
  drawer.value.visible = false;
  // 关闭弹出框的时候，需要通知父组件更新 v-model 绑定的数据
  emits('confirm');
};
</script>

<template>
  <el-drawer id="v-drawer" v-model="drawer.visible" :title="drawer.title" :size="drawer.size"
             :direction="drawer.direction"
             :append-to-body="true"
             @close="close" @open="open">
    <slot name="default"/>
    <slot name="footer"/>
  </el-drawer>
</template>

<style scoped>
#v-drawer > header {
  margin-bottom: 0 !important;
}
</style>